﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebCore.Models.ViewModels.Account;
using WebCore.Models.DataManagers;
using WebCore.App_Start;
using WebCore.Models.DataEntities;
using WebCore.Helpers;


namespace WebCore.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Login()
        {
            HttpCookie rememberMe = Request.Cookies["rememberme"];
            HttpCookie userName = Request.Cookies["userName"];
            HttpCookie password = Request.Cookies["password"];

            if (rememberMe != null && userName != null && password != null)
            {
                ViewBag.UserName = userName.Value;
                ViewBag.Password = password.Value;
                ViewBag.RememberMe = Boolean.Parse(rememberMe.Value);
            }
            else
            {
                ViewBag.UserName = string.Empty;
                ViewBag.Password = string.Empty;
                ViewBag.RememberMe = false;
            }
            LoginViewModel viewModel = new LoginViewModel();
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Login(string txtUserName, string txtPassword, bool chkRemember, string ReturnUrl)
        {
            if (!System.Web.Security.Membership.ValidateUser(txtUserName, txtPassword))
            {
                bool isLocked = false;
                UserDetail ud = AccountManager.GetUserDetail(txtUserName, ref isLocked);

                if (ud.State == MyAppConfig.State_Active)
                {
                    // remember cookie
                    HttpCookie rememberMe = Request.Cookies["rememberme"];
                    if (rememberMe != null) { rememberMe.Expires = DateTime.Now.AddHours(-20); rememberMe.Value = false.ToString(); }

                    HttpCookie userName = Request.Cookies["userName"];
                    if (userName != null) { userName.Expires = DateTime.Now.AddHours(-20); userName.Value = String.Empty; }

                    HttpCookie password = Request.Cookies["password"];
                    if (password != null) { password.Expires = DateTime.Now.AddHours(-20); password.Value = String.Empty; }

                    if (chkRemember == true)
                    {
                        HttpCookie newRememberMe = new HttpCookie("rememberme", chkRemember.ToString());
                        newRememberMe.Expires = DateTime.Today.AddMonths(12);
                        Response.Cookies.Add(newRememberMe);
                        //
                        HttpCookie newUserName = new HttpCookie("userName", txtUserName);
                        newUserName.Expires = DateTime.Today.AddMonths(12);
                        Response.Cookies.Add(newUserName);
                        //
                        HttpCookie newPassword = new HttpCookie("password", txtPassword);
                        newPassword.Expires = DateTime.Today.AddMonths(12);
                        Response.Cookies.Add(newPassword);
                    }
                    else if (rememberMe != null && userName != null && password != null)
                    {
                        Response.Cookies.Add(rememberMe);
                        Response.Cookies.Add(userName);
                        Response.Cookies.Add(password);
                    }
                    //

                    FormsAuthentication.SetAuthCookie(txtUserName, chkRemember);
                    if (string.IsNullOrEmpty(ReturnUrl))
                        return Redirect("/Home/Index");
                    else
                        return Redirect(ReturnUrl);
                }
                else if (ud.State == MyAppConfig.State_Inactive)
                {
                    ViewBag.UserName = txtUserName;
                    ViewBag.Password = txtPassword;
                    ViewBag.RememberMe = chkRemember;
                    ViewBag.ErrorMessage = Resources.Front.Error_NotActiveUser;
                    return View();
                }
                else if (ud.State == MyAppConfig.State_Locked)
                {
                    ViewBag.UserName = txtUserName;
                    ViewBag.Password = txtPassword;
                    ViewBag.RememberMe = chkRemember;
                    ViewBag.ErrorMessage = Resources.Front.Error_LockedUser;
                    return View();
                }
                else
                {
                    ViewBag.UserName = txtUserName;
                    ViewBag.Password = txtPassword;
                    ViewBag.RememberMe = chkRemember;
                    ViewBag.ErrorMessage = Resources.Front.Error_DeletedUser;
                    return View();
                }
            }
            else
            {
                // check active user
                MembershipUser mu = System.Web.Security.Membership.GetUser(txtUserName);
                bool isLocked = false;
                UserDetail ud = AccountManager.GetUserDetail(txtUserName, ref isLocked);
                //
                if (isLocked)
                {
                    ViewBag.UserName = txtUserName;
                    ViewBag.Password = txtPassword;
                    ViewBag.RememberMe = chkRemember;
                    ViewBag.ErrorMessage = Resources.Front.Error_LockedUser;
                    return View();
                }
                else
                {
                    if (ud != null && ud.State == MyAppConfig.State_Locked)
                    {
                        ViewBag.UserName = txtUserName;
                        ViewBag.Password = txtPassword;
                        ViewBag.RememberMe = chkRemember;
                        ViewBag.ErrorMessage = Resources.Front.Error_LockedUser;
                        return View();
                    }

                    if (mu != null)
                    {
                        if (mu.IsApproved == false)
                        {
                            ViewBag.UserName = txtUserName;
                            ViewBag.Password = txtPassword;
                            ViewBag.RememberMe = chkRemember;
                            ViewBag.ErrorMessage = Resources.Front.Error_NotActiveUser;
                            return View();
                        }
                    }
                    
                    ViewBag.ErrorMessage = Resources.Front.Error_InvalidUsernamePassword;
                    ViewBag.UserName = txtUserName;
                    ViewBag.Password = txtPassword;
                    ViewBag.RememberMe = chkRemember;
                    return View();
                }
            }
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return Redirect("/Account/Login");
        }

        public ActionResult Register()
        {
            RegisterViewModel viewModel = new RegisterViewModel();
            viewModel.PartialView = "Account/_Register01";
            return View(viewModel);
        }
        [HttpPost]
        public ActionResult Register(RegisterViewModel viewModel, string submitButton)
        {
            if (submitButton == "Register01Confirm" && viewModel.Register01Agree == true)
            {
                viewModel.PartialView = "Account/_Register02";
            }
            else if (submitButton == "Register02Confirm")
            {
                viewModel.PartialView = "Account/_Register02";
                if (ModelState.IsValid)
                {
                    string errorCode = string.Empty;
                    if (AccountManager.IsValidUser(viewModel, ref errorCode))
                    {
                        Guid activeCode = Guid.NewGuid();
                        try
                        {
                            // send activate email 
                            
                            //
                            UserDetail userDetail = AccountManager.CreateUser(viewModel, activeCode);
                            //
                            viewModel.PartialView = "Account/_Register03";
                        }
                        catch (Exception ex)
                        {
                            ModelState.AddModelError("Email", Resources.Front.Error_CanNotSendEmail);
                        }
                    }
                    else
                    {
                        if (errorCode == "NotMatchPassword")
                            ModelState.AddModelError("PasswordConfirm", Resources.Front.Error_PasswordDoNotMatch);
                        else if (errorCode == "ExistedUserName")
                            ModelState.AddModelError("UserName", Resources.Front.Error_ExistedUserName);
                        else if (errorCode == "ExistedEmail")
                            ModelState.AddModelError("Email", Resources.Front.Error_ExistedEmail);
                    }

                }
                else
                {
                    return View(viewModel);
                }
            }

            return View(viewModel);
        }

        public ActionResult Activate(string username, string code)
        {
            ActivateViewModel viewModel = new ActivateViewModel();
            viewModel.UserName = username;
            viewModel.IsSuccess = AccountManager.Activate(username, code);
            return View(viewModel);
        }

        public ActionResult ForgetPassword()
        {
            ForgetPasswordViewModel viewModel = new ForgetPasswordViewModel();
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult ForgetPassword(ForgetPasswordViewModel viewModel)
        {
            string newPassword = string.Empty;
            string userName = string.Empty;
            viewModel.IsSuccess = AccountManager.ResetPassword(viewModel.Email, ref newPassword, ref userName);
            if (viewModel.IsSuccess.Value == true)
            {
                //string subject = NewsManager.GetSettingValue(NewsCategoryGroupEnum.SettingsAccountForgetPasswordEmailSubject, MyAppConfig.Lang_Current);
                //string content = NewsManager.GetStaticPage(NewsCategoryGroupEnum.StaticAccountForgetPasswordEmailTemplate, MyAppConfig.Lang_Current);
                //content = content.Replace("[Password]", newPassword).Replace("[Account]", userName);
                //EmailHelper.SendEmail(viewModel.Email, subject, content);
            }
            return View(viewModel);
        }
    }
}
